#include("../layout.html")
#@layout("编辑分类目录")

#define head()
<style>
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }
</style>
#end

#define body()
<h1 class="wp-heading-inline">编辑分类目录</h1>
<hr class="wp-header-end">

<div class="layui-fluid">
    <form class="layui-form tby-form-left" id="edit-term-form">
        <input type="hidden" name="id" id="termId">
        <input type="hidden" name="taxonomy" value="category">

        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block" style="width:400px;">
                <input type="text" name="name" id="name" required lay-verify="required" placeholder="请输入分类名称" autocomplete="off" class="layui-input">
            </div>
            <p>这将是它在站点上显示的名字。</p>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">别名</label>
            <div class="layui-input-block" style="width:400px;">
                <input type="text" name="slug" id="slug" placeholder="分类别名（可选）" autocomplete="off" class="layui-input">
            </div>
            <p>"别名"是在URL中使用的别称，它可以令URL更美观。通常使用小写，只能包含字母，数字和连字符（-）。</p>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">父级分类目录</label>
            <div class="layui-input-block" style="width:400px;">
                <select name="parentId" id="parent" lay-verify="">
                    <option value="0">无</option>
                    <!-- 选项将通过JavaScript动态加载 -->
                </select>
            </div>
            <p>分类目录和标签不同，它可以有层级关系。您可以有一个"音乐"分类目录，在这个目录下可以有叫做"流行"和"古典"的子目录。</p>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block" style="width:400px;">
                <textarea name="description" id="description" placeholder="分类描述（可选）" class="layui-textarea"></textarea>
            </div>
            <p>描述只会在一部分主题中显示。</p>
        </div>

        <div class="layui-form-item">
            <button type="submit" lay-submit lay-filter="edit-term" class="layui-btn layui-btn-sm">更新分类目录</button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="cancel-edit">取消</button>
        </div>
    </form>
</div>
#end

#define foot()
<script>
    layui.define(['tbynet'], function(exports) {
        'use strict';

        const $ = layui.$;
        const form = layui.form;
        const layer = layui.layer;
        const tbynet = layui.tbynet;

        /**
         * 分类编辑模块
         */
        const TermEditor = {
            termId: null,

            // API 端点
            endpoints: {
                get: '/admin/api/term/get',
                update: '/admin/api/term/update',
                hierarchy: '/admin/api/term/hierarchy'
            },

            /**
             * 初始化编辑页面
             */
            init() {
                this.termId = this.getUrlParam('id');
                if (!this.termId) {
                    layer.msg('未找到分类ID', { icon: 2 });
                    return;
                }

                this.bindEvents();
                this.loadTermData();
                this.loadParentDropdown();
            },

            /**
             * 绑定事件
             */
            bindEvents() {
                // 表单提交
                form.on('submit(edit-term)', (data) => {
                    this.updateTerm(data.field);
                    return false;
                });

                // 取消按钮
                $('#cancel-edit').on('click', () => {
                    this.goBack();
                });
            },

            /**
             * 获取URL参数
             */
            getUrlParam(name) {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get(name);
            },

            /**
             * 加载分类数据
             */
            loadTermData() {
                this.showLoading();

                tbynet.ajax(this.endpoints.get, {
                    id: this.termId,
                    taxonomy: 'category'
                }, (res) => {
                    this.hideLoading();
                    if (res.state) {
                        this.populateForm(res.data);
                    } else {
                        layer.msg(res.msg || '加载分类数据失败', { icon: 2 });
                    }
                }, "json").fail(() => {
                    this.hideLoading();
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 加载父级分类下拉框
             */
            loadParentDropdown() {
                tbynet.ajax(this.endpoints.hierarchy, {
                    taxonomy: 'category'
                }, (res) => {
                    if (res.state) {
                        this.renderParentDropdown(res.data);
                    }
                }, "json").fail(() => {
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 渲染父级分类下拉框
             */
            renderParentDropdown(data) {
                const $parentSelect = $('#parent');
                // 清空除了第一个选项之外的所有选项
                $parentSelect.find('option:not(:first)').remove();

                const renderOptions = (terms, depth = 0) => {
                    terms.forEach(term => {
                        // 不能选择自己作为父级
                        if (term.termId == this.termId) return;

                        const indent = '— '.repeat(depth);
                        const $option = $(`<option value="${term.termId}">${indent}${term.name}</option>`);
                        $parentSelect.append($option);

                        if (term.children && term.children.length > 0) {
                            renderOptions(term.children, depth + 1);
                        }
                    });
                };

                renderOptions(data.hierarchyTerms || []);
                form.render('select');
            },

            /**
             * 填充表单数据
             */
            populateForm(termData) {
                $('#termId').val(termData.termId);
                $('#name').val(termData.name || '');
                $('#slug').val(termData.slug || '');
                $('#description').val(termData.description || '');

                // 设置父级分类
                setTimeout(() => {
                    $('#parent').val(termData.parentId || 0);
                    form.render('select');
                }, 100);
            },

            /**
             * 更新分类
             */
            updateTerm(formData) {
                this.showLoading();

                tbynet.ajax(this.endpoints.update, formData, (res) => {
                    this.hideLoading();
                    if (res.state) {
                        layer.msg(res.msg, {
                            icon: 1,
                            time: 1000
                        }, () => {
                            this.goBack();
                        });
                    } else {
                        layer.msg(res.msg || '更新失败', { icon: 2 });
                    }
                }, "json").fail(() => {
                    this.hideLoading();
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 返回上一页
             */
            goBack() {
                window.location.href = '/web/admin/term';
            },

            /**
             * 显示加载状态
             */
            showLoading() {
                if ($('.loading-overlay').length === 0) {
                    $('body').append(`
                        <div class="loading-overlay">
                            <div class="loading-content">
                                <i class="layui-icon layui-icon-loading layui-anim-rotate"></i>
                                <div>加载中...</div>
                            </div>
                        </div>
                    `);
                }
            },

            /**
             * 隐藏加载状态
             */
            hideLoading() {
                $('.loading-overlay').remove();
            }
        };

        // 初始化编辑页面
        $(document).ready(() => {
            TermEditor.init();
        });
    });
</script>
#end